package demo1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：黄淼淳
 * @description：资源类
 * @date ：2021/12/12 19:01
 */
public class Resource {
    private int number = 0;

    public synchronized void add() throws InterruptedException {
        while (number > 0)
            this.wait();
        number++;
        System.out.println(number);
        this.notifyAll();
    }

    public synchronized void del() throws InterruptedException {
        while (number <= 0)
            this.wait();
        number--;
        System.out.println(number);
        this.notifyAll();
    }

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0)
                condition.await();
            number++;
            System.out.println(Thread.currentThread().getName() + "==" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number <= 0)
                condition.await();
            number--;
            System.out.println(Thread.currentThread().getName() + "=" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
